from qturboframe.lib.report.log import logger
from qturboframe.lib.webdriver.exceptions import SeleniumError
from qturboframe.lib.utils.check import CheckBasic
from qturboframe.lib.utils.assertion import Assertion
from qturboframe.lib.utils.CustomError.custom_error import CustomError
from qturboframe.public_ui.base_element import BaseElement


class Message(BaseElement, CheckBasic):
    '''消息框操作类'''

    def __init__(self, element_para, father=None, timeout=5):
        try:
            super().__init__(element_para, father=father, timeout=timeout)
        except SeleniumError as msg:
            logger.debug(str(msg))
            self._element = None

    def exist(self):
        '''
        判断消息框是否存在

        :Returns:
            存在则返回True，不存在则返回False

        :Example:
         - 例: message.exist()
        '''
        if self._element:
            return True
        else:
            return False

    def get_text(self):
        '''
        获取消息框中的消息文本

        :Returns:
            返回消息文本

        :Example:
         - 例: message.get_text()
        '''
        try:
            content_div = self._element.find_element_by_attribute(
                'css selector', 'div.h-message-custom-content', timeout=self.timeout)
            return content_div.text
        except Exception as msg:
            logger.warn(str(msg))
            return None

    def close(self):
        '''
        关闭消息框

        :Example:
         - 例: message.close()
        '''
        try:
            close_btn = self._element.find_element_by_attribute(
                'css selector', 'a.h-message-notice-close', timeout=self.timeout)
            close_btn.secure_click()
        except Exception as msg:
            raise SeleniumError(CustomError.Error_EQ03014000_Message_Fail_Close)

    def check(self, ui_expect):
        '''
        检查信息内容

        :Args:
         - ui_expect: 界面期望值

        :Raises:
            检查不通过抛出SeleniumError异常

        :Example:
         - 例: message.check('新增成功')
        '''
        ui_value = self.get_text()
        try:
            Assertion(ui_expect).check_string(ui_value)
        except AssertionError:
            message = '界面取值为{}，期望值为{}，弹出的信息提示与期望不一致！'.format(ui_value, ui_expect)
            raise SeleniumError(CustomError.Error_EQ03010001_Verify_Expect_Actual_Not_Equal, message)

    def match_check(self, ui_expect):
        '''
        检查信息内容

        :Args:
         - ui_expect: 界面期望值

        :Raises:
            检查不通过抛出SeleniumError异常

        :Example:
         - 例: message.check('新增成功')
        '''
        ui_value = self.get_text()
        try:
            Assertion(ui_expect).match_string(ui_value)
        except AssertionError:
            message = '界面取值为{}，期望值为{}，弹出的信息提示与期望不一致！'.format(ui_value, ui_expect)
            raise SeleniumError(CustomError.Error_EQ03010001_Verify_Expect_Actual_Not_Equal, message)

